<template>
  <div id="app">
    <div>
      <span>姓名:</span>
      <input type="text" v-model="names" />
    </div>
    <div>
      <span>年龄:</span>
      <input type="number" v-model.number="ages" />
    </div>
    <div>
      <span>性别:</span>
      <select v-model="gender">
        <option value="男">男</option>
        <option value="女">女</option>
      </select>
    </div>
    <div>
      <!-- <button @click="isShow ? fn : upFn(ides)">添加/修改</button> -->
      <button @click="addFn()">添加/修改</button>
    </div>
    <div>
      <table border="1" cellpadding="10" cellspacing="0">
        <tr>
          <th>序号</th>
          <th>姓名</th>
          <th>年龄</th>
          <th>性别</th>
          <th>操作</th>
        </tr>
        <tr v-for="(item, index) in arr" :key="index">
          <td>{{ index + 1 }}</td>
          <td>{{ item.name }}</td>
          <td>{{ item.age }}</td>
          <td>{{ item.sex }}</td>
          <td>
            <button @click="san(index)">删除</button>
            <button @click="xian(index)">编辑</button>
          </td>
        </tr>
      </table>
    </div>
  </div>
</template>
<script>
export default {
  data() {
    return {
      arr: [
        {
          name: "张三",
          age: 17,
          sex: "男",
        },
        {
          name: "李四",
          age: 12,
          sex: "男",
        },
        {
          name: "王五",
          age: 21,
          sex: "男",
        },
        {
          name: "小七",
          age: 17,
          sex: "男",
        },
      ],
      names: "",
      ages: "",
      gender: "男",
      isShow: false,
    };
  },
  methods: {
    addFn() {
      if (this.isShow === false) {
        if (this.names.trim().length == 0 || this.ages <= 0) {
          alert("请输入完整内容");
          return;
        }
        //增加
        this.arr.push({
          name: this.names,
          age: this.ages,
          sex: this.gender,
        });
        (this.names = ""), (this.ages = "");
      } else {
        //修改
        this.arr.splice(this.isShow, 1, {
          name: this.names,
          age: this.ages,
          sex: this.gender,
        });
        (this.isShow = false), (this.names = ""), (this.ages = "");
      }
    },
    //删除
    san(id) {
      console.log(id);
      this.arr.splice(id, 1);
    },
    //回显
    xian(ids) {
      this.names = this.arr[ids].name;
      this.ages = this.arr[ids].age;
      this.gender = this.arr[ids].sex;
      this.isShow = ids;
    },
  },
};
</script>